<template>
  <view class="selector-container">
    <!-- 状态指示器 -->
    <view class="status-indicator" :class="statusClass">
      {{ statusText }}
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-overlay">
      <view class="loading-spinner"></view>
      <view class="loading-text">{{ loadingText }}</view>
    </view>

    <!-- Konva画布容器 -->
    <view class="canvas-container">
      <view id="konva-container" class="konva-stage"></view>

      <!-- 添加框选框按钮 -->
      <view class="add-box-btn" @tap="addNewSelectionBox" v-if="rotation === 0">
        <text class="add-icon">+</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-toolbar">
      <button class="toolbar-btn btn-cancel" @tap="handleCancel">取消</button>
      <button class="toolbar-btn btn-confirm" @tap="handleConfirm">确定</button>
      <button class="toolbar-btn btn-rotate" @tap="handleRotate">旋转</button>
    </view>
  </view>
</template>

<script>
import {
  loadImage,
  calculateImageBounds,
  getImageInfo,
  rotateImage,
  base64ToImage,
} from "@/utils/image-utils.js";
import {
  relativeToAbsolute,
  generateId,
  validateCoordinates,
} from "@/utils/coordinate-utils.js";
import {
  createStage,
  createImageLayer,
  createSelectionLayer,
  createMaskLayer,
  createKonvaImage,
  createSelectionBox,
  addSelectionBoxEvents,
  getSelectionCoordinates,
  clearLayer,
  destroyStage,
  updateScreenshotMask,
  createRotatedMask,
} from "@/utils/konva-utils.js";

export default {
  data() {
    return {
      // 基础数据
      imageUrl: "", // 原始图片URL
      currentImageSrc: "", // 当前显示的图片源（可能是旋转后的base64）
      coordinates: [],

      // Konva相关
      stage: null,
      imageLayer: null,
      selectionLayer: null,
      maskLayer: null,
      konvaImage: null,

      // 图片信息
      imageInfo: null, // 当前显示图片的信息
      originalImageInfo: null, // 原始图片信息（不变）
      imageBounds: null,

      // 状态管理
      loading: false,
      loadingText: "加载中...",
      rotation: 0, // 当前旋转角度
      isDragging: false,

      // 容器尺寸
      containerWidth: 0,
      containerHeight: 0,
    };
  },

  computed: {
    statusClass() {
      if (this.isDragging) return "status-dragging";
      if (this.rotation !== 0) return "status-rotated";
      return "status-normal";
    },

    statusText() {
      if (this.isDragging) return "拖拽状态 - 实时反馈";
      if (this.rotation !== 0) return `旋转状态 - ${this.rotation}°`;
      return "正常状态 - 显示框选框";
    },
  },

  onLoad(options) {
    // 获取传递的参数
    if (options.image) {
      this.imageUrl = decodeURIComponent(options.image);
    }
    if (options.coordinates) {
      try {
        this.coordinates = JSON.parse(decodeURIComponent(options.coordinates));
      } catch (e) {
        console.error("解析坐标数据失败:", e);
        this.coordinates = [];
      }
    }

    console.log("接收到的数据:", {
      // imageUrl: this.imageUrl,
      coordinates: this.coordinates,
    });
  },

  onReady() {
    this.$nextTick(() => {
      this.initializeCanvas();
    });
  },

  onUnload() {
    // 清理资源
    this.cleanup();
  },

  methods: {
    // 初始化画布
    async initializeCanvas() {
      try {
        this.loading = true;
        this.loadingText = "初始化画布...";

        // 获取容器尺寸
        await this.getContainerSize();

        // 创建Konva舞台
        this.stage = createStage(
          "konva-container",
          this.containerWidth,
          this.containerHeight
        );
        this.imageLayer = createImageLayer();
        this.maskLayer = createMaskLayer();
        this.selectionLayer = createSelectionLayer();

        this.stage.add(this.imageLayer);
        this.stage.add(this.maskLayer);
        this.stage.add(this.selectionLayer);

        // 加载图片
        await this.loadAndDisplayImage();

        // 绘制初始框选框
        this.drawSelectionBoxes();

        this.loading = false;
      } catch (error) {
        console.error("初始化画布失败:", error);
        this.loading = false;
        uni.showToast({
          title: "初始化失败",
          icon: "error",
        });
      }
    },

    // 获取容器尺寸
    getContainerSize() {
      return new Promise((resolve) => {
        const query = uni.createSelectorQuery().in(this);
        query
          .select(".canvas-container")
          .boundingClientRect((data) => {
            if (data) {
              this.containerWidth = data.width;
              this.containerHeight = data.height;
            } else {
              // 默认尺寸
              this.containerWidth = 375;
              this.containerHeight = 600;
            }
            resolve();
          })
          .exec();
      });
    },

    // 加载并显示图片
    async loadAndDisplayImage() {
      this.loadingText = "加载图片...";

      // 获取原始图片信息并保存
      this.originalImageInfo = await getImageInfo(this.imageUrl);
      this.imageInfo = { ...this.originalImageInfo };
      this.currentImageSrc = this.imageUrl;

      // 加载图片元素
      const imageElement = await loadImage(this.currentImageSrc);

      // 计算图片在画布中的显示边界
      this.imageBounds = calculateImageBounds(
        this.imageInfo.width,
        this.imageInfo.height,
        this.containerWidth,
        this.containerHeight
      );

      // 创建Konva图片对象
      this.konvaImage = createKonvaImage(
        imageElement,
        this.imageBounds,
        0 // 初始旋转角度为0，因为我们不再使用Konva的旋转
      );

      // 添加到图层
      this.imageLayer.add(this.konvaImage);
      this.imageLayer.batchDraw();
    },

    // 绘制框选框
    drawSelectionBoxes() {
      if (this.rotation !== 0) {
        // 旋转状态下不显示框选框
        return;
      }

      // 清空现有框选框
      clearLayer(this.selectionLayer);

      // 验证坐标数据 (传入true表示使用相对坐标0-1范围验证)
      if (!validateCoordinates(this.coordinates)) {
        console.warn("坐标数据格式不正确");
        return;
      }

      // 注意：坐标数据是相对于图片实际分辨率的，需要转换为画布上的坐标

      // 绘制每个框选框
      this.coordinates.forEach((coord) => {
        const absoluteCoord = relativeToAbsolute(
          coord,
          this.imageBounds.width,
          this.imageBounds.height,
          this.imageInfo.width,
          this.imageInfo.height
        );

        // 调整坐标到图片位置
        absoluteCoord.x += this.imageBounds.x;
        absoluteCoord.y += this.imageBounds.y;

        // 创建框选框
        const selectionBox = createSelectionBox(absoluteCoord, coord.id);
        selectionBox.name("selection-box");

        // 添加事件监听，使用函数方式传递imageBounds以便动态获取
        addSelectionBoxEvents(
          selectionBox,
          () => this.imageBounds, // 返回当前的imageBounds
          this.onDragStart,
          this.onDragEnd,
          this.onResize,
          this.onDragMove
        );

        // 添加删除事件
        this.addDeleteEvent(selectionBox);

        // 添加到图层
        this.selectionLayer.add(selectionBox);
      });

      this.selectionLayer.batchDraw();

      // 更新遮罩层
      this.updateMask();
    },

    // 拖拽开始
    onDragStart(selectionBox) {
      this.isDragging = true;
      console.log("开始拖拽:", selectionBox.id());
    },

    // 拖拽移动（实时更新）
    onDragMove(selectionBox) {
      // 实时更新遮罩
      this.updateMask();
    },

    // 拖拽结束
    onDragEnd(selectionBox) {
      this.isDragging = false;
      console.log("结束拖拽:", selectionBox.id());

      // 更新坐标数据
      this.updateCoordinatesFromBoxes();

      // 更新遮罩
      this.updateMask();
    },

    // 调整大小
    onResize(selectionBox) {
      console.log("调整大小:", selectionBox.id());

      // 更新坐标数据
      this.updateCoordinatesFromBoxes();

      // 更新遮罩
      this.updateMask();
    },

    // 添加删除事件
    addDeleteEvent(selectionBox) {
      const deleteHandler = (e) => {
        e.cancelBubble = true;

        const boxId = selectionBox.id();

        // 从坐标数组中移除
        this.coordinates = this.coordinates.filter(
          (coord) => coord.id !== boxId
        );

        // 销毁框选框
        selectionBox.destroy();

        // 安全地重绘图层
        if (this.selectionLayer) {
          this.selectionLayer.batchDraw();
        }

        // 更新遮罩
        this.updateMask();

        console.log("删除框选框:", boxId);
      };

      selectionBox.deleteButton.on("click tap", deleteHandler);
      selectionBox.deleteIcon.on("click tap", deleteHandler);
    },

    // 从框选框更新坐标数据
    updateCoordinatesFromBoxes() {
      const currentCoords = getSelectionCoordinates(
        this.selectionLayer,
        this.imageBounds,
        this.imageInfo.width,
        this.imageInfo.height
      );

      // 更新坐标数组，保持原有顺序
      this.coordinates = this.coordinates.map((coord) => {
        const updated = currentCoords.find((c) => c.id === coord.id);
        return updated || coord;
      });

      console.log("更新后的坐标:", this.coordinates);
    },

    // 更新遮罩层
    updateMask() {
      if (!this.maskLayer || !this.stage) return;

      const stageBounds = {
        width: this.containerWidth,
        height: this.containerHeight,
      };

      if (this.rotation !== 0) {
        // 旋转状态下不显示框选，只显示图片区域遮罩
        createRotatedMask(
          this.maskLayer,
          stageBounds,
          this.imageBounds,
          0 // 图片本身已旋转，不需要额外的旋转角度
        );
      } else if (this.selectionLayer) {
        // 正常状态下使用带洞的遮罩
        updateScreenshotMask(
          this.maskLayer,
          this.selectionLayer,
          stageBounds,
          this.imageBounds
        );
      }
    },

    // 处理旋转
    async handleRotate() {
      try {
        this.loading = true;
        this.loadingText = "旋转图片中...";
        
        // 更新旋转角度
        this.rotation = (this.rotation + 90) % 360;
        console.log("旋转到:", this.rotation);

        // 生成旋转后的图片base64
        const rotatedBase64 = await rotateImage(this.currentImageSrc, 90);
        this.currentImageSrc = rotatedBase64;

        // 更新图片信息（宽高可能交换）
        const rotatedImageElement = await base64ToImage(rotatedBase64);
        this.imageInfo = {
          width: rotatedImageElement.naturalWidth,
          height: rotatedImageElement.naturalHeight,
          path: rotatedBase64
        };

        // 重新计算图片在画布中的显示边界
        this.imageBounds = calculateImageBounds(
          this.imageInfo.width,
          this.imageInfo.height,
          this.containerWidth,
          this.containerHeight
        );

        // 更新Konva图片对象
        if (this.konvaImage) {
          // 移除旧的图片
          this.konvaImage.remove();
        }

        // 创建新的Konva图片对象
        this.konvaImage = createKonvaImage(
          rotatedImageElement,
          this.imageBounds,
          0 // 不使用Konva的旋转，因为图片本身已经旋转了
        );

        // 添加到图层并重绘
        this.imageLayer.add(this.konvaImage);
        this.imageLayer.batchDraw();

        // 旋转时隐藏框选；回到0度时重绘框选
        this.drawSelectionBoxes();

        // 更新遮罩
        this.updateMask();
        
        this.loading = false;
      } catch (error) {
        console.error("旋转图片失败:", error);
        this.loading = false;
        uni.showToast({
          title: "旋转失败",
          icon: "error",
        });
      }
    },

    // 添加新框选框
    addNewSelectionBox() {
      if (this.rotation !== 0 || !this.imageBounds || !this.imageInfo) return;

      // 创建新的框选框坐标（在图片中央）
      // 注意：坐标是相对于图片实际分辨率的，不是相对于显示尺寸
      const newCoord = {
        id: generateId(),
        x: 0.35, // 图片中央偏左一点
        y: 0.35, // 图片中央偏上一点
        width: 0.3, // 30%宽度
        height: 0.3, // 30%高度
      };

      // 添加到坐标数组
      this.coordinates.push(newCoord);

      // 重新绘制框选框
      this.drawSelectionBoxes();

      console.log("添加新框选框:", newCoord);
    },

    // 处理取消
    handleCancel() {
      uni.showModal({
        title: "确认取消",
        content: "取消后将丢失所有修改，确定要取消吗？",
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack();
          }
        },
      });
    },

    // 处理确定
    handleConfirm() {
      // 更新最新坐标
      this.updateCoordinatesFromBoxes();

      // 准备返回数据
      const result = {
        coordinates: this.coordinates,
        rotationAngle: this.rotation,
        originalImageUrl: this.imageUrl, // 原始图片URL
        currentImageSrc: this.currentImageSrc, // 当前显示的图片（可能是旋转后的base64）
        originalImageInfo: this.originalImageInfo, // 原始图片信息
        currentImageInfo: this.imageInfo, // 当前图片信息
      };

      console.log("提交数据:", result);

      // 这里可以通过事件总线或其他方式传递数据给父组件
      // 或者通过页面参数返回

      uni.showToast({
        title: "保存成功",
        icon: "success",
      });

      // setTimeout(() => {
      //   uni.navigateBack();
      // }, 1500);
    },

    // 清理资源
    cleanup() {
      if (this.stage) {
        destroyStage(this.stage);
        this.stage = null;
        this.imageLayer = null;
        this.maskLayer = null;
        this.selectionLayer = null;
        this.konvaImage = null;
      }
    },
  },
};
</script>

<style scoped>
.selector-container {
  position: relative;
  height: 100vh;
  background: #1a1a1a;
  color: #ffffff;
  overflow: hidden;
}

.status-indicator {
  position: absolute;
  top: 20px;
  left: 20px;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  z-index: 10;
  backdrop-filter: blur(10px);
}

.status-normal {
  background: rgba(0, 255, 136, 0.2);
  color: #00ff88;
  border: 1px solid #00ff88;
}

.status-rotated {
  background: rgba(255, 149, 0, 0.2);
  color: #ff9500;
  border: 1px solid #ff9500;
}

.status-dragging {
  background: rgba(0, 122, 255, 0.2);
  color: #007aff;
  border: 1px solid #007aff;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 100;
  backdrop-filter: blur(5px);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-top: 4px solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loading-text {
  color: #ffffff;
  font-size: 16px;
}

.canvas-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.konva-stage {
  width: 100%;
  height: 100%;
}

.add-box-btn {
  position: absolute;
  bottom: 100px;
  right: 20px;
  width: 56px;
  height: 56px;
  background: #007aff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 16px rgba(0, 122, 255, 0.3);
  z-index: 10;
  transition: all 0.3s ease;
}

.add-box-btn:active {
  transform: scale(0.95);
  background: #0056b3;
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.5);
}

.add-icon {
  color: white;
  font-size: 28px;
  font-weight: bold;
  line-height: 1;
}

.bottom-toolbar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 80px;
  background: #2c2c2c;
  border-top: 1px solid #3a3a3c;
  display: flex;
  align-items: center;
  padding: 0 20px;
  gap: 12px;
}

.toolbar-btn {
  flex: 1;
  height: 44px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-cancel {
  background: #1a1a1a;
  color: #ffffff;
  border: 1px solid #3a3a3c;
}

.btn-cancel:active {
  background: #3a3a3c;
}

.btn-confirm {
  background: #007aff;
  color: white;
}

.btn-confirm:active {
  background: #0056b3;
}

.btn-rotate {
  background: #ff9500;
  color: white;
}

.btn-rotate:active {
  background: #cc7a00;
}

/* 响应式设计 */
@media (max-width: 414px) {
  .status-indicator {
    top: 10px;
    left: 10px;
    font-size: 12px;
    padding: 6px 12px;
  }

  .bottom-toolbar {
    padding: 0 15px;
    gap: 8px;
  }

  .toolbar-btn {
    font-size: 14px;
    height: 40px;
  }
}
</style>
